﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls;
using System.Text;

using FRL.DebtChased.Repository;
using FRL.DebtChased.Repository.PartModels;
using FRL.DebtChased.Website;

namespace FRL.DebtChased.Website.FinanceParts
{

	/// <summary>
	/// Declaration of FinCommissionTable class
	/// </summary>
	public class FinCommissionTable : BaseWebPart
	{

		/////////////////////////////////////////////////////////////
		// Constants and enumerations

		protected const string ExpandButtonId = "butExpand";

		/////////////////////////////////////////////////////////////
		// Attributes - Stored in User Data

		private FinCommissionModel.eScope m_Scope = FinCommissionModel.eScope.TopLevel;
		[WebBrowsable(false)]
		[Personalizable(PersonalizationScope.User)]
		public FinCommissionModel.eScope Scope
		{
			get { return m_Scope; }
			set { m_Scope = value; this.Title = _composeTitle(); }
		}

		private int m_iUserId = 0;
		[WebBrowsable(false)]
		[Personalizable(PersonalizationScope.User)]
		public int UserId
		{
			get { return m_iUserId; }
			set { m_iUserId = value; this.Title = _composeTitle(); }
		}

		/////////////////////////////////////////////////////////////
		// Attributes

		// Dynamic controls
		private Button m_butExpand;
		private Menu m_menuScope;

		/////////////////////////////////////////////////////////////
		// Construction

		public FinCommissionTable()
			: base("Commission Table", eMode.WithGrid)
		{

			// Initialize member variables
			this.Title = _composeTitle();

		}

		/////////////////////////////////////////////////////////////
		// Implementation

		protected override int ContentWidth
		{
			get { return 800; }
		}

		protected override int ContentHeight
		{
			get { return 0; }
		}

		protected override string GrivViewSkinId
		{
			get { return "FinCommissionGridView"; }
		}

		protected override void _createControls()
		{

			// Call base-class function
			base._createControls();

			// If this is a user control, always create the m_cboUser object,
			// or it will spoil the viewstate data

			// Expand button
			m_butExpand = new Button();
			m_butExpand.Text = "Expand...";
			m_butExpand.ID = ExpandButtonId;
			m_butExpand.Click += new EventHandler(Expand_Click);

			// Scope menu
			m_menuScope = new Menu();
			m_menuScope.SkinID = "GeneralMenu";
			m_menuScope.Items.Add(new MenuItem("Scope"));
			m_menuScope.MenuItemClick += new MenuEventHandler(MenuScope_MenuItemClick);

			// Add top-level to menu
			MenuItem newMenu = new MenuItem("Top Level","0");
			m_menuScope.Items[0].ChildItems.Add(newMenu);

			// Add managers to menu
			newMenu = new MenuItem();
			newMenu.Text = "Managers";
			newMenu.ChildItems.Add(new MenuItem("Hank", "12"));
			newMenu.ChildItems.Add(new MenuItem("Casper", "14"));
			newMenu.ChildItems.Add(new MenuItem("Hello", "15"));
			m_menuScope.Items[0].ChildItems.Add(newMenu);

			// Add users to menu
			newMenu = new MenuItem();
			newMenu.Text = "Collectors";
			newMenu.ChildItems.Add(new MenuItem("Fred", "12"));
			newMenu.ChildItems.Add(new MenuItem("Dave", "14"));
			newMenu.ChildItems.Add(new MenuItem("Mary", "15"));
			m_menuScope.Items[0].ChildItems.Add(newMenu);

			// Add to controls
			Controls.Add(m_butExpand);
			Controls.Add(m_menuScope);

		}

		protected override void _fillContent(System.Web.UI.HtmlTextWriter w, GridView gridView)
		{

			// Build a table
			w.Write("<table border='0' cellspacing='0' cellpadding='0'");
				w.Write("<tr>");
					w.Write("<td colspan='2' align='center' valign='top'>");
						gridView.RenderControl(w);
					w.Write("</td>");
					w.Write("<td rowspan='2'>&nbsp;</td>");
					w.Write("<td rowspan='2'><img src='../Images/graphicSample.jpg' />");					
					w.Write("</td>");
				w.Write("</tr>");
				w.Write("<tr>");
					w.Write("<td align='left' valign='center'>");
						m_menuScope.RenderControl(w);
					w.Write("</td>");
					w.Write("<td align='right' valign='center'>");
						m_butExpand.RenderControl(w);
					w.Write("</td>");
				w.Write("</tr>");
			w.Write("</table>");

		}

		protected override void _bindGrid(GridView gridView)
		{

			// Shortcuts
			if (gridView.DataSource != null)
				return;
			if (m_model == null)
				return;

			// Set up grid
			gridView.DataKeyNames = new string[1] { "UserId" };
			gridView.DataSource = (m_model as FinCommissionModel).Elements;
			gridView.DataBind();

		}

		protected override void _setFooterCells(GridViewRow row)
		{

			// Set totals
			row.Cells[8].Text = "Total:";
			row.Cells[9].Text = (m_model as FinCommissionModel).TotalSubTotal.ToString("BC",null);
			row.Cells[11].Text = (m_model as FinCommissionModel).TotalToGo.ToString("BC", null);
			row.Cells[12+1].Text = (m_model as FinCommissionModel).TotalConfirmedToday.ToString("BC", null);

		}

		protected override void _loadModel()
		{

			// Get repository
			DebtChasedEntities ent = base._getEnt();

			// Load the model
			m_model = new FinCommissionModel(ent, m_Scope, m_iUserId);

		}

		/////////////////////////////////////////////////////////////
		// Event Handlers

		void MenuScope_MenuItemClick(object sender, MenuEventArgs e)
		{

			// Get the user id
			int iUserId = 0;
			if (!int.TryParse(e.Item.Value, out iUserId))
				return;

			// TODO
			// This code needs review

			/*
			// Update the part
			if (iUserId == 0)
			{
				m_Scope = FinCommissionModel.eScope.TopLevel;
				m_iUserId = 0;
			}
			else
			{
				FRLUser user = new FRLUser() { Roles = (int)FRLUser.eRoles.FIN_SUPERUSER };
					// _getRep().GetUser(iUserId);
				if (user.Contains(FRLUser.eRoles.FIN_MNGADMIN | FRLUser.eRoles.FIN_SUPERUSER | FRLUser.eRoles.FIN_SYSADMIN | FRLUser.eRoles.FIN_USERADMIN))
					m_Scope = FinCommissionModel.eScope.Manager;
				else
					m_Scope = FinCommissionModel.eScope.User;
				m_iUserId = iUserId;
			}
			 */

			// Set the title
			//this.Title = _composeTitle();

			// Remove any residual model from the session
			//MySession.BindMySession().ClearModel(base.UniqueID);

		}

		void Expand_Click(object sender, EventArgs e)
		{

			// Go to the commission page
			HttpContext.Current.Response.Redirect("~/Finance/CommissionChart.aspx");

		}


		/////////////////////////////////////////////////////////////
		// Operations

		private string _composeTitle()
		{

			// Build a title
			StringBuilder sb = new StringBuilder();

			// TODO
			// This code needs review

			/*
			// If need to loop up user names
			string strUserFullName = null;
			if ((m_Scope == FinCommissionModel.eScope.Manager) || (m_Scope == FinCommissionModel.eScope.User))
			{
				if(m_iUserId!=0)
					strUserFullName = _getRep().GetUserDescription(m_iUserId);
			}

			// Compare scopes
			sb.Append("Commission - ");
			switch (m_Scope)
			{
				case FinCommissionModel.eScope.TopLevel:
					sb.Append("Top Level");
					break;
				case FinCommissionModel.eScope.Manager:
					sb.AppendFormat("Manager, {0}", strUserFullName);
					break;
				case FinCommissionModel.eScope.User:
					sb.AppendFormat("Collector, {0}", strUserFullName);
					break;
			} // switch
			 */

			// Return string
			return sb.ToString();

		}

	}

}